package com.geralt.im.tool;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonTool {

	private static ObjectMapper om;
	
	private static JsonTool jsonTool = null;
	private JsonTool(){
		om = new ObjectMapper();
	}
	
	public synchronized static JsonTool getInstance(){
		if(jsonTool==null){
			jsonTool = new JsonTool();
		}
		return jsonTool;
	}
	
	public String objectToString(Object obj){
		
		String value = null;
		try {
			value = om.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return value;
	}
	
	public Object stringToObject(String str,Class clz){
		Object obj=null;
		try {
			obj = om.readValue(str, clz);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return obj;
	}
	
	
	public Object stringToObjects(String str,Class<?> parametrized, Class<?>... parameterClasses){
		Object obj=null;
		try {
			JavaType javaType = om.getTypeFactory().constructParametricType(parametrized, parameterClasses);
			obj = om.readValue(str, javaType);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return obj;
	}
}
